package com.cyurs.netty.dubborpc.netty;

import com.cyurs.netty.dubborpc.consumer.ClientBootStrap;
import com.cyurs.netty.dubborpc.provider.HelloServerImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/30
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取客户端发送的消息，并调用我们的服务
        System.out.println("msg=" + msg);
        /**
         *  客户端在调用服务器的api时，我们需要定义一个协议
         *  如：
         *      要求每次发消息时，必须以某个字符串开头“Hello#Cyrus#”
         */
        if (msg.toString().startsWith(ClientBootStrap.providerName)) {
            String result = new HelloServerImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
